<?php

declare(strict_types=1);

namespace App\Controller\Home\Drp;

use AdaPaySdk\Payment;
use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use App\Model\BalanceOrder;
use App\Model\ChargeDetail;
use App\Model\ChargeOption;
use App\Model\Device;
use App\Model\Order;
use App\Model\Station;
use App\Services\Iot\IotService1;
use App\Services\Iot\IotService1 as IotService;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;
use App\Model\Distributors;

class HomeDeviceController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Station $station;

    #[Inject]
    protected ChargeOption $chargeOption;

    #[Inject]
    protected Distributors $distributors;

    #[Inject]
    protected Device $device;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**我的设备统计
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function statics(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        if($info['level'] == Distributors::LEVEL_2){
           $data['all'] =  $this->device->where('child_distributor_id',$info['id'])->count();
            $data['inline'] =  $this->device->where('inline',1)
                ->where('child_distributor_id',$info['id'])->count();
            $data['off'] =  $this->device->where('child_distributor_id',$info['id'])
                ->where('inline',0)->count();
        }else{
            $data['all'] =  $this->device
                ->where('distributor_id',$info['id'])
                    // 通过whereRaw添加条件，仅当child_distributor_id > 0时，要求is_disabled为0
                ->whereRaw('IF(child_distributor_id > 0, is_disabled = 0, true)')
                ->count();
            $data['inline'] =  $this->device
                ->where('distributor_id',$info['id'])
                ->whereRaw('IF(child_distributor_id > 0, is_disabled = 0, true)')
                ->where('inline',1)
                ->count();
            $data['off'] =  $this->device
                ->where('distributor_id',$info['id'])
                ->whereRaw('IF(child_distributor_id > 0, is_disabled = 0, true)')
                ->where('inline',0)
                ->count();
        }
        return $this->success($data);
    }

    /**经销商设备列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function list(RequestInterface $request):ResponseInterface{
        $page = $request->inputs(['page','limit','keyword','distributor_id','inline','is_active']);
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $data['list'] = $this->device->where(function ($query) use ($page,$info) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('sn', 'like', '%' . $page['keyword'] . '%');
            }
            if($page['inline'] != ''){
                $query->where('inline',$page['inline']);
            }
            if($page['is_active'] != ''){
                $query->where('is_active',$page['is_active']);
            }
            if($info['level'] == Distributors::LEVEL_1){
                $query->where('distributor_id',$info['id']);
                if(array_key_exists('distributor_id',$page) && $page['distributor_id'] > 0){
                    $query->where('child_distributor_id',$page['distributor_id']);
                    $query->where('is_disabled',0);
                }else{
                    // 通过whereRaw添加条件，仅当child_distributor_id > 0时，要求is_disabled为0
                    $query->whereRaw('IF(child_distributor_id > 0, is_disabled = 0, true)');
                }
            }else{
                $query->where('child_distributor_id',$info['id']);
            }
        })->orderBy('station_id','desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get(['id','sn','iot_sn','signal','inline','is_active','channel','charge_id','active_at','expires_at',
                'distributor_id','child_distributor_id','station_id','is_new','sp_rec_mon','channel'])->toArray();
        foreach($data['list'] as $k => $v){
            if($data['list'][$k]['station_id']){
                $data['list'][$k]['station'] =Station::where('id',$v['station_id'])->first(['name','address']);
            }
        }
        $data['total'] = $this->device->where(function ($query) use ($page,$info) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('sn', 'like', '%' . $page['keyword'] . '%');
                $query->orWhere('iot_sn', 'like', '%'.$page['keyword'].'%');
            }
            if($page['inline'] !== ''){
                $query->where('inline',$page['inline']);
            }
            if($page['is_active'] !== ''){
                $query->where('is_active',$page['is_active']);
            }
            if($info['level'] == Distributors::LEVEL_1){
                $query->where('distributor_id',$info['id']);
                if(array_key_exists('distributor_id',$page) && $page['distributor_id'] > 0){
                    $query->where('child_distributor_id',$page['distributor_id']);
                    $query->where('is_disabled',0);
                }else{
                    // 通过whereRaw添加条件，仅当child_distributor_id > 0时，要求is_disabled为0
                    $query->whereRaw('IF(child_distributor_id > 0, is_disabled = 0, true)');
                }
            }else{
                $query->where('child_distributor_id',$info['id']);
            }
        })->count();

        foreach($data['list'] as $k => $v){
            if($data['list'][$k]['child_distributor_id']){
                $data['list'][$k]['distributor_name'] = $this->distributors->where('id',$data['list'][$k]['child_distributor_id'])
                    ->value('name');
            }else{
                $data['list'][$k]['distributor_name'] = $this->distributors->where('id',$data['list'][$k]['distributor_id'])
                    ->value('name');
            }
        }
        return $this->success($data);
    }

    /**设备管理---编辑
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function edit(RequestInterface $request):ResponseInterface{
        $params = $request->inputs(['is_refund','is_active','sn']);
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        if(!isset($params['sn'])){
            return $this->error('1001','设备编号不能为空');
        }
        if($info['level'] == Distributors::LEVEL_1){
            $device = $this->device->where('sn',$params['sn'])
                ->where('distributor_id',$info['id'])
                ->where('child_distributor_id',0)
                ->first();
        }else{
            $device = $this->device->where('sn',$params['sn'])
                ->where('child_distributor_id',$info['id'])
                ->first();
        }
        if(!$device){
            return $this->error('1002','您的设备下暂无此编号');
        }
        $device->is_refund = $params['is_refund'];
        $device->is_active = $params['is_active'];
        $device->save();
        return $this->success();
    }


    public function del(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $deviceId = $request->input('device_id',0,'int');
        if(!$deviceId){
            return $this->error(code:1001,msg:'登录态失效 请重新登录');
        }
        Device::where('id',$deviceId)->update(['is_del',0]);
        return $this->success();
    }

    /**读取配置
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function readParams(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $deviceId = $request->input('device_id',0,'int');
        if(!$deviceId){
            return $this->error('1001','缺少参数设备id');
        }
        $device = $this->device->where('id', $deviceId )->first();
        if($device){
            IotService::readParams($device->iot_sn);
            return $this->success(msg:'读取成功 请稍后查看');
        }
        return $this->error('1002','读取失败');

    }

    /**设备详情
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function detail(RequestInterface $request):ResponseInterface{
        $sn = $request->input('sn');
        $sn = trim($sn);
        if(!$sn){
            return $this->error(1001,'设备编号不能为空');
        }
        $device = $this->device->where('sn',$sn)->first(['id','sn','iot_sn','station_id','charge_id','is_active','sp_rec_mon','signal','is_refund'])->toArray();
        if(!$device){
            return $this->error(1001,'设备不存在');
        }
        if($device['station_id']){
            $device['station'] = $this->station->where('id',$device['station_id'])
                ->first(['address','lat','lng','name','images']);
        }else{
            $device['station'] = [];
        }
        $device['number'] = Order::where('device_id',$device['id'])->count();
        if($device['charge_id']){
            $device['charge'] = $this->chargeOption
                ->where('id',$device['charge_id'])
                ->first(['id','name','is_autoload','fee'])
                ->toArray();
            $device['charge']['power_children'] = ChargeDetail::where('charge_option_id',$device['charge_id'])
                ->where('type',ChargeDetail::POWER_TYPE)
                ->orderBy('sort','desc')->get(['id','minutes','min_power','max_power','charge_option_id'])->toArray();
            $device['charge']['time_children'] = ChargeDetail::where('charge_option_id',$device['charge_id'])
                ->where('type',ChargeDetail::TIME_TYPE)
                ->orderBy('sort','desc')->get(['id','minutes','fee','charge_option_id'])->toArray();
        }else{
            $device['charge'] = [];
        }
        return $this->success($device);
    }

    /**默认设备参数
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function normalParams(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $deviceId = $request->input('device_id');
        if(!$deviceId){
            return $this->error('1001','缺少参数设备id');
        }
        $device = $this->device->where('id', $deviceId )
            ->first(['id','sn','iot_sn','params_read_at','is_refund',
                'coin_min','card_min','coin_elec','card_elec','cst','sp_full_empty']);
        if($device){
            return $this->success($device);
        }
        return $this->error('1002','设备不存在');
    }

    /**更新投币相关参数
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function updateParams(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $params = $request->inputs(['device_id','coin_min','card_min','coin_elec','card_elec','cst','sp_full_empty']);
        $device = $this->device->find($params['device_id']);
        try{
            if($device){
                unset($params['device_id']);
                $device->update($params);
                $device->updateParams();
                return $this->success(msg:'更新成功 请稍后查看');
            }
            return $this->error('1002','设备不存在');
        }catch (\Exception $e){
            return $this->error('1001','操作繁忙 请稍后重试');
        }
    }

    /**设置设备套餐
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function setCharge(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $params = $request->inputs(['device_id','charge_id']);
        if(!$params['device_id']){
            return $this->error('1001','设备id不能为空');
        }
        if(!$params['charge_id']){
            $params['charge_id'] = 0;
        }
        $device = $this->device->where('id',$params['device_id'])->first();
        if($device){
            $device->charge_id = $params['charge_id'];
            $device->save();
            return $this->success(msg:'修改套餐成功');
        }
        return $this->error('1002','设备不存在');
    }

    /**自己的设备
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function selfList(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        if($info['level'] == Distributors::LEVEL_1){
            $data = $this->device->where('distributor_id',$info['id'])
                ->where('child_distributor_id',0)
                ->where('is_active',1)
                ->get(['id','sn','iot_sn']);
        }else{
            $data = $this->device->where('child_distributor_id',$info['id'])
                ->where('is_active',1)
                ->get(['id','sn','iot_sn']);
        }
        return $this->success($data);
    }


    /**我的设备订单
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function orderList(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $page = $request->inputs(['sn','page','limit','start','end','status','distributor_id']);

        if(!$page['distributor_id']){
            $page['distributor_id'] = $info['id'];
        }
        $data['list'] = Order::where(function ($query) use ($page) {
            $query->where('is_draw',0);
            if (array_key_exists('start', $page) && $page['start']) {
                $query->where('created_at', '>=', $page['start']);
            }
            if (array_key_exists('end', $page) && $page['end']) {
                $query->where('created_at', '<=', $page['end']);
            }
            if (array_key_exists('status', $page) && $page['status']) {
                $query->where('status', $page['status']);
            }
            if(isset($page['sn']) && $page['sn']){
                $query->where('sn', $page['sn']);
            }else{
                $query->where('distributor_id',$page['distributor_id']);
            }
            })
           ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->orderBy('id','desc')
            ->get(['number','channel_number','sn','station_id','payment_type',
                'estimate_stop_at','stop_at','duration_seconds','device_id',
                'fee','power_fee','service_fee','return_fee','original_fee','minutes',
                'out_ord_id','status','is_return_fee','charge_detail_id','is_check',
                'charge_id','coupon_record_id','power','stop_reason','is_autoload'])
            ->toArray();
        $data['total'] = Order::where(function ($query) use ($page) {
                $query->where('is_draw',0);
                if (array_key_exists('start', $page) && $page['start']) {
                    $query->where('created_at', '>=', $page['start']);
                }
                if (array_key_exists('end', $page) && $page['end']) {
                    $query->where('created_at', '<=', $page['end']);
                }
                if (array_key_exists('status', $page) && $page['status']) {
                    $query->where('status', $page['status']);
                }
                if(isset($page['sn']) && $page['sn']){
                    $query->where('sn', $page['sn']);
                }else{
                    $query->where('distributor_id',$page['distributor_id']);
                }
            })->count();
        foreach($data['list'] as $k => $v ){
            $data['list'][$k]['station'] = Station::where('id',$v['station_id'])->first(['name','address']);
            if($v['charge_detail_id']){
                $data['list'][$k]['chargeDetail'] = ChargeDetail::where('id',$v['charge_detail_id'])->first();
            }
            $deviceModel = Device::where('id',$v['device_id'])->first();
            $data['list'][$k]['power_children'] = ChargeDetail::where('charge_option_id',$v['charge_id'])
                ->where('type',ChargeDetail::POWER_TYPE)
                ->orderBy('sort','desc')->get(['id','minutes','min_power','max_power','charge_option_id'])->toArray();
            if($deviceModel->child_distributor_id){
                $data['list'][$k]['customer_service_phone'] = Distributors::where('id',$deviceModel->child_distributor_id)->value('customer_service_phone');
            }else{
                $data['list'][$k]['customer_service_phone'] = Distributors::where('id',$deviceModel->distributor_id)->value('customer_service_phone');
            }
        }
        return $this->success($data);
    }


    /**
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function balanceList(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if (!$info) {
            return $this->error(code: '400', msg: '登录态失效 请重新登录');
        }
        $page = $request->inputs(['page','limit','status','start','end']);
        if($info['level'] == Distributors::LEVEL_1){
            $devices = Device::where('distributor_id',$info['id'])
                ->get(['id']);
        }else{
            $devices = Device::where('child_distributor_id',$info['id'])
                ->get(['id']);
        }
        $inDevices = [];
        $data['list'] =[];
        $data['total'] = 0;
        if($devices){
            foreach($devices as $k => $v){
                $inDevices[] = $v['id'];
            }
            $data['list'] = BalanceOrder::whereIn('device_id',$inDevices)
                ->where(function ($query) use ($page) {
                    if (array_key_exists('start', $page) && $page['start']) {
                        $query->where('created_at', '>=', $page['start']);
                    }
                    if (array_key_exists('end', $page) && $page['end']) {
                        $query->where('created_at', '<=', $page['end']);
                    }
                    if($page['status']){
                        $query->where('status', $page['status']);
                    }
                })
                ->offset(($page['page'] - 1) * $page['limit'])
                ->limit($page['limit'])
                ->get()->toArray();
            foreach($data['list'] as $k => $v){
                $data['list'][$k]['sn'] = $this->device
                    ->where('id',$v['device_id'])
                    ->value('sn');
            }
            $data['total'] = BalanceOrder::whereIn('device_id',$inDevices)
                ->where(function ($query) use ($page) {
                    if (array_key_exists('start', $page) && $page['start']) {
                        $query->where('created_at', '>=', $page['start']);
                    }
                    if (array_key_exists('end', $page) && $page['end']) {
                        $query->where('created_at', '<=', $page['end']);
                    }
                    if($page['status']){
                        $query->where('status', $page['status']);
                    }
                })
                ->count();
        }
        return $this->success($data);
    }

}
